package com.ssm.basis.service.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.TypeDescriptor;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * int.class = Integer.TYPE != Integer.class
 * https://blog.csdn.net/f641385712/category_10625150.html
 */
public abstract class TypeConversionHelper {
    static ConversionService conversionService;

    public static <R> IPage<R> castPage(Object page, Class<R> clazz) {
        return ((IPage<?>) page).convert(clazz::cast);
    }

    public static <R> List<R> castList(Object collection, Class<R> clazz) {
        return ((Collection<?>) collection).stream().map(clazz::cast).collect(Collectors.toList());
    }

    public static <K, V> Map<K, V> castMap(Object map, Class<K> clazzK, Class<V> clazzV) {
        return ((Map<?, ?>) map).entrySet().stream().collect(Collectors.toMap(
                x -> clazzK.cast(x.getKey()), x -> clazzV.cast(x.getValue())
        ));
    }

    public static Object convert(Object object) {
        TypeDescriptor sourceTypeDesp = TypeDescriptor.forObject(object);
        TypeDescriptor targetTypeDesp = TypeDescriptor.collection(List.class, TypeDescriptor.valueOf(Object.class));
        return conversionService.convert(object, sourceTypeDesp, targetTypeDesp);
    }

    @Autowired
    void setConversionService(ConversionService conversionService) {
        TypeConversionHelper.conversionService = conversionService;
    }
}